<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70%" :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="200px"
      v-loading="formLoading"
      scroll-to-error
    >
      <h3 class="mb-4 font-medium">门店基本信息</h3>

      <el-form-item label="门店名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入门店名称" />
      </el-form-item>

      <el-form-item label="门店LOGO" prop="logo">
          <UploadImg v-model="formData.logo" :limit="1" />
          <div class="text-xs text-gray-400">提示: 100*100px或正方型图片 (必填)</div>
      </el-form-item>

      <el-form-item label="门店banner图" prop="storeBanner">
        <UploadImgs v-model="formData.storeBanner" :limit="10" />
        <div class="text-xs text-gray-400">提示: 宽度自适应,高度76px</div>
      </el-form-item>

      <el-form-item label="门店广告图" prop="storeAdvertisement">
        <UploadImgs v-model="formData.storeAdvertisement" :limit="10" />
      </el-form-item>

      <el-form-item label="资质" prop="businessLicense">
        <UploadImg v-model="formData.businessLicense" :limit="1" />
        <div class="text-xs text-gray-400">提示: 上传营业执照或其他资质证明</div>
      </el-form-item>

      <el-form-item label="门店地址" prop="areaId">
         <!-- :options="areaList" 通过 API 获取地区数据 -->
         <el-cascader v-model="formData.areaId" :options="areaList" :props="cascaderProps" placeholder="请选择省/市/区/街道" class="w-full"/>
      </el-form-item>

      <el-form-item label="详细地址(门牌号)" prop="detailAddress">
        <el-input v-model="formData.detailAddress" placeholder="请输入详细地址" />
      </el-form-item>

      <!-- Use nested form items within a flex container for single-line layout with required indicators -->
      <el-form-item label="定位" required>
        <div style="display: flex; align-items: center; width: 100%;">
          <el-form-item prop="longitude" style="margin-bottom: 0; margin-right: 8px; flex-grow: 0; flex-shrink: 0;">
            <el-input
              v-model="formData.longitude"
              placeholder="经度"
              class="!w-200px"
              type="number"
              :controls="false"
            />
          </el-form-item>
          <el-form-item prop="latitude" style="margin-bottom: 0; margin-right: 8px; flex-grow: 0; flex-shrink: 0;">
            <el-input
              v-model="formData.latitude"
              placeholder="纬度"
              class="!w-200px"
              type="number"
              :controls="false"
            />
          </el-form-item>
          <el-button type="primary" @click="openMapDialog" style="flex-shrink: 0;">选择坐标</el-button>
        </div>
      </el-form-item>

       <el-form-item label="店铺电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入店铺电话" />
       </el-form-item>

       <el-form-item label="门店公告" prop="introduction">
          <el-input
            v-model="formData.introduction"
            :rows="3"
            type="textarea"
            placeholder="请输入门店公告"
          />
       </el-form-item>

      <el-form-item label="营业时间" prop="openingHours">
          <el-time-picker
            v-model="formData.openingHours"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
          />
      </el-form-item>

       <el-form-item label="身份证正面" prop="idCardFront">
         <UploadImg v-model="formData.idCardFront" :limit="1" />
       </el-form-item>

       <el-form-item label="身份证反面" prop="idCardBack">
         <UploadImg v-model="formData.idCardBack" :limit="1" />
       </el-form-item>

       <el-form-item label="其他图片" prop="storePhotosOther">
         <UploadImgs v-model="formData.storePhotosOther" :limit="10" />
       </el-form-item>

      <el-divider />
      <h3 class="mb-4 font-medium">状态与设置</h3>

      <el-form-item label="经营状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="0">营业</el-radio>
          <el-radio :label="1">休息</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-divider />
      <h3 class="mb-4 font-medium">门店账户设置</h3>

      <el-form-item label="管理员手机号" prop="storeMgPhone">
        <el-input
          v-model="formData.storeMgPhone"
          autocomplete="new-password"
          placeholder="请输入管理员登录手机号"
        />
      </el-form-item>

      <el-form-item label="管理员密码" prop="storeMgPw">
        <el-input
          v-model="formData.storeMgPw"
          type="password"
          show-password
          autocomplete="new-password"
          :placeholder="formType === 'update' ? '无需修改请留空' : '请输入管理员登录密码'"
        />
        <div v-if="formType === 'update'" class="text-xs text-gray-400">提示: 不输入则不修改密码</div>
      </el-form-item>

      <el-divider />
      <h3 class="mb-4 font-medium">门店营业设置</h3>

      <el-form-item label="配送方式" prop="deliveryExpress">
        <el-checkbox v-model="formData.deliveryExpress">快递配送</el-checkbox>
        <el-checkbox v-model="formData.deliverySelfPickup">门店自提</el-checkbox>
        <el-checkbox v-model="formData.deliveryStore">门店配送</el-checkbox>
        <el-checkbox v-model="formData.deliveryPickupPoint">自提点提货</el-checkbox>
      </el-form-item>

      <el-form-item label="收银台支付跳转链接H5" prop="paymentH5Url">
         <el-input v-model="formData.paymentH5Url" placeholder="用户下单支付后, 跳转到指定的页面" />
         <div class="text-xs text-gray-400 mt-1">当用户下单支付后，跳转到指定的页面，默认跳转到商城首页</div>
      </el-form-item>

      <el-form-item label="收银台支付跳转链接-小程序" prop="paymentMiniPath">
          <el-input v-model="formData.paymentMiniPath" placeholder="用户下单支付后, 跳转到指定的页面" />
           <div class="text-xs text-gray-400 mt-1">当用户下单支付后，跳转到指定的页面</div>
      </el-form-item>

       <el-form-item label="门店首页显示" prop="showConsultation">
        <el-checkbox v-model="formData.showConsultation">店铺咨询</el-checkbox>
        <el-checkbox v-model="formData.showShopping">进店选购</el-checkbox>
      </el-form-item>

      <el-form-item label="公司AI舌诊总剩余次数" prop="companyTotalTimes">
        <el-input
          v-model="formData.companyTotalTimes"
          placeholder="系统自动显示"
          readonly
          disabled
        />
        <div class="text-xs text-gray-400 mt-1">系统显示的剩余次数，不可编辑</div>
      </el-form-item>

      <el-form-item label="门店AI舌诊次数" prop="aiTongueTimes">
        <el-input-number
          v-model="formData.aiTongueTimes"
          :min="0"
          :max="10000000"
          placeholder="请输入门店AI舌诊次数"
          class="!w-full"
        />
        <div class="text-xs text-gray-400 mt-1">设置门店可使用的AI舌诊次数</div>
      </el-form-item>

      <el-divider />
      <h3 class="mb-4 font-medium">门店详情</h3>
      <!-- 移除 label, 添加 class 用于居中 -->
      <!-- Conditionally render Editor to ensure it mounts after data is potentially loaded -->
      <el-form-item v-if="formData.id || formType === 'create'" prop="storeDetail" class="">
        <Editor v-model="formData.storeDetail" />
      </el-form-item>

      <el-divider />
      <h3 class="mb-4 font-medium">其他设置</h3>
      <el-form-item label="快递通知类型" prop="expressNotifyType">
        <el-radio-group v-model="formData.expressNotifyType">
          <el-radio :label="1">寄件人</el-radio>
          <el-radio :label="2">收件人</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="寄件人手机号" prop="expressNotifyPhone">
        <el-input v-model="formData.expressNotifyPhone" placeholder="请输入寄件人手机号" />
        <div class="text-xs text-gray-400 mt-1">用于快递实用虚拟号时查询物流信息</div>
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    <!-- 地图弹窗 -->
    <el-dialog v-model="mapDialogVisible" title="获取经纬度" append-to-body @close="mapDialogVisible = false">
      <IFrame v-if="tencentLbsUrl" class="h-609px" :src="tencentLbsUrl" />
      <div v-else>地图加载中或配置错误...</div>
    </el-dialog>
  </Dialog>
</template>
<script setup lang="ts">
import { reactive, ref, nextTick, onMounted, onUnmounted, watch } from 'vue'
import * as DeliveryPickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore/index'
import { CommonStatusEnum } from '@/utils/constants'
import { getAreaTree, AreaVO } from '@/api/system/area'
import * as ConfigApi from '@/api/mall/trade/config'
import { ElCascader, ElMessage } from 'element-plus' // 引入 ElMessage (如果使用)
import Editor from '@/components/Editor/src/Editor.vue' // 导入富文本编辑器
import { log } from 'console'
import { assign } from 'lodash-es' // Ensure lodash-es is imported if used elsewhere or add it

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const mapDialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const tencentLbsUrl = ref('')
const tencentLbsKey = ref('') // Store the key
const formRef = ref()
const areaList = ref<AreaVO[]>([]) // 明确类型
// Cascader props
const cascaderProps = {
  value: 'id', // ID 字段名
  label: 'name', // 名称字段名
  children: 'children', // 子节点字段名
  checkStrictly: false, // 是否严格选择，false 表示只能选叶子节点
  emitPath: false // 只返回选中的节点ID，而不是整个路径数组
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm() // 重置表单
  // 加载区域数据 (如果尚未加载)
  if (areaList.value.length === 0) {
    const rawData = await getAreaTree()
    areaList.value = rawData
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      // 注意：密码通常不在编辑时回显
      const data = await DeliveryPickUpStoreApi.getDeliveryPickUpStore(id)
      console.log('API Data:', data); // Log API response

      // 处理 areaId
      let areaPath: number[] | undefined = undefined;
      if (data.areaId) {
        try {
          areaPath = await findAreaPath(data.areaId, areaList.value);
          console.log('Found Area Path:', areaPath);
        } catch (e) {
          console.error("Error finding area path:", e);
          message.error('加载区域信息失败，请检查区域数据');
        }
      } else {
        console.log('No areaId in API data');
      }

      // 处理开业时间
      let openingHoursArray = defaultFormData.openingHours; // Default
      if (data.openingHours && Array.isArray(data.openingHours) && data.openingHours.length === 2) {
        // 假设API返回 'HH:mm:ss', 格式化为 'HH:mm'
        openingHoursArray = data.openingHours.map(time => time ? time.substring(0, 5) : '');
      } else if (data.startTime && data.endTime) {
        // 或者如果API返回单独的开始/结束时间
        openingHoursArray = [data.startTime.substring(0, 5), data.endTime.substring(0, 5)];
      }

      // Transform comma-separated strings to arrays for UploadImgs
      const storeBannerArray = data.storeBanner ? data.storeBanner.split(',').filter(url => url) : [];
      const storeAdvertisementArray = data.storeAdvertisement ? data.storeAdvertisement.split(',').filter(url => url) : [];
      const storePhotosOtherArray = data.storePhotosOther ? data.storePhotosOther.split(',').filter(url => url) : [];

      // 赋值给 formData
      formData.value = {
        ...defaultFormData, // 从默认值开始
        ...data,             // 展开API数据，覆盖默认值
        areaId: data.areaId, // 重要：这里使用 API 返回的原始 areaId，级联组件会处理路径
        openingHours: openingHoursArray, // 使用处理后的营业时间数组
        storeBanner: storeBannerArray, // Use transformed array
        storeAdvertisement: storeAdvertisementArray, // Use transformed array
        storePhotosOther: storePhotosOtherArray, // Use transformed array
        storeMgPw: '',       // 密码在编辑时不回显
        // 显式处理布尔值，防止 null 或 undefined 覆盖默认值 (?? 操作符)
        status: data.status ?? 0,
        operatingStatus: data.operatingStatus ?? 1,
        deliveryExpress: data.deliveryExpress ?? true,
        deliverySelfPickup: data.deliverySelfPickup ?? true,
        deliveryStore: data.deliveryStore ?? true,
        deliveryPickupPoint: data.deliveryPickupPoint ?? true,
        showConsultation: data.showConsultation ?? true,
        showShopping: data.showShopping ?? true,
        expressNotifyType: data.expressNotifyType ?? 2,
        longitude: data.longitude ?? defaultFormData.longitude,
        latitude: data.latitude ?? defaultFormData.latitude,
        companyTotalTimes: data.companyTotalTimes ?? 0,
        aiTongueTimes: data.aiTongueTimes ?? 0
      };
      console.log('Assigned FormData:', JSON.parse(JSON.stringify(formData.value))); // Log final formData

    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const defaultFormData = {
  id: undefined,
  name: '',
  logo: '',
  storeBanner: [], // Use array for UploadImgs v-model
  storeAdvertisement: [], // Use array for UploadImgs v-model
  businessLicense: '', // Single image URL for business license
  areaId: undefined,
  detailAddress: '',
  longitude: null, // Use null or '' as default
  latitude: null,
  phone: '',
  status: 0,
  introduction: '',
  openingHours: ['07:50', '23:50'], // [startTime, endTime] in HH:mm format
  announcement: '',
  idCardFront: '',
  idCardBack: '',
  storePhotosOther: [], // Array for UploadImgs
  storeMgPhone: '', // 管理员手机号
  storeMgPw: '', // 管理员密码
  operatingStatus: 1, // 默认营业
  deliveryExpress: true,
  deliverySelfPickup: true,
  deliveryStore: true,
  deliveryPickupPoint: true,
  paymentH5Url: '', // Renamed from h5RedirectUrl
  paymentMiniPath: '', // Renamed from mpRedirectUrl
  showConsultation: true, // 默认显示店铺咨询
  showShopping: true, // 默认显示进店选购
  storeDetail: '', // Use storeDetail for rich text content
  expressNotifyType: 2, // 快递通知类型: 1-寄件人, 2-收件人 (默认收件人)
  expressNotifyPhone: '', // Renamed from senderMobile
  companyTotalTimes: 0, // 当前AI舌诊次数剩余次数（只读）
  aiTongueTimes: 0 // 门店AI舌诊次数（可编辑）
}
const formData = ref(assign({}, defaultFormData))

const formRules = reactive({
  name: [{ required: true, message: '门店名称不能为空', trigger: 'blur' }],
  logo: [{ required: true, message: '门店LOGO不能为空', trigger: 'change' }],
  areaId: [{ required: true, message: '门店地址不能为空', trigger: 'change' }],
  detailAddress: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
  phone: [
    { required: true, message: '店铺电话不能为空', trigger: 'blur' },
    // 考虑座机等多种格式，可放宽或使用更复杂的正则
    { pattern: /^[0-9\\s-]+$/, message: '请输入有效的电话号码', trigger: 'blur' }
  ],
  introduction: [{ required: true, message: '门店介绍不能为空', trigger: 'blur' }],
  openingHours: [{ required: true, message: '营业时间不能为空', trigger: 'change' }],
  storeMgPhone: [
    { required: true, message: '管理员手机号不能为空', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  storeMgPw: [
    // 创建时必填，编辑时可选填（不填则不修改）
    { required: formType.value === 'create', message: '管理员密码不能为空', trigger: 'blur' },
    // 可以添加密码复杂度校验
    { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
  ],
  operatingStatus: [{ required: true, message: '经营状态不能为空', trigger: 'change' }],
  deliveryExpress: [{ required: true, message: '请选择是否支持快递配送', trigger: 'change' }],
  deliverySelfPickup: [{ required: true, message: '请选择是否支持门店自提', trigger: 'change' }],
  deliveryStore: [{ required: true, message: '请选择是否支持门店配送', trigger: 'change' }],
  deliveryPickupPoint: [{ required: true, message: '请选择是否支持自提点提货', trigger: 'change' }],
  paymentH5Url: [
    {
      required: false, // According to provided info, these are not mandatory
      message: 'H5支付跳转链接不能为空',
      trigger: 'blur'
    }
  ],
  paymentMiniPath: [
    {
      required: false, // According to provided info, these are not mandatory
      message: '小程序支付跳转链接不能为空',
      trigger: 'blur'
    }
  ],
  showConsultation: [{ required: true, message: '请选择是否显示店铺咨询', trigger: 'change' }],
  showShopping: [{ required: true, message: '请选择是否显示进店选购', trigger: 'change' }],
  expressNotifyType: [{ required: true, message: '请选择快递通知类型', trigger: 'change' }],
  expressNotifyPhone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  aiTongueTimes: [
    { required: false, message: '门店AI舌诊次数不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === null || value === undefined || value === '') {
          callback()
        } else if (isNaN(Number(value)) || Number(value) < 0 || Number(value) > 10000000) {
          callback(new Error('请输入有效的次数 (0-10000000)'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  status: [{ required: true, message: '经营状态不能为空', trigger: 'change' }],
  longitude: [
    { required: true, message: '经度不能为空', trigger: ['blur', 'change'] },
    {
      validator: (rule, value, callback) => {
        if (value === null || value === '') {
           callback()
        } else if (isNaN(Number(value)) || Number(value) < -180 || Number(value) > 180) {
          callback(new Error('请输入有效的经度 (-180 到 180)'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  latitude: [
    { required: true, message: '纬度不能为空', trigger: ['blur', 'change'] },
     {
      validator: (rule, value, callback) => {
         if (value === null || value === '') {
            callback()
         } else if (isNaN(Number(value)) || Number(value) < -90 || Number(value) > 90) {
           callback(new Error('请输入有效的纬度 (-90 到 90)'))
         } else {
           callback()
         }
      },
      trigger: ['blur', 'change']
    }
  ],
})

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) {
      message.warning("请检查表单必填项！");
      return
  }
  formLoading.value = true
  try {
    // 准备提交的数据
    const dataToSubmit = {
      ...formData.value,
      // 直接使用 formData 中的 areaId (因为 emitPath: false)
      areaId: formData.value.areaId,
      // 如果后端需要 startTime/endTime, 从 openingHours 数组转换
      // 注意：如果后端可以直接接受 openingHours: ['HH:mm', 'HH:mm']，则下面两行和删除操作可以省略
      openingTime: formData.value.openingHours ? formData.value.openingHours[0] : null, // 使用 null 或 undefined 根据后端要求
      closingTime: formData.value.openingHours ? formData.value.openingHours[1] : null,
      // Transform arrays back to comma-separated strings *after* spreading formData
      storeBanner: formData.value.storeBanner ? formData.value.storeBanner.join(',') : '',
      storeAdvertisement: formData.value.storeAdvertisement ? formData.value.storeAdvertisement.join(',') : '',
      storePhotosOther: formData.value.storePhotosOther ? formData.value.storePhotosOther.join(',') : '',
    }
    // 如果后端不需要 openingHours 数组，则删除它
    delete dataToSubmit.openingHours

    if (formType.value === 'create') {
      await DeliveryPickUpStoreApi.createDeliveryPickUpStore(dataToSubmit)
      message.success(t('common.createSuccess'))
    } else {
      await DeliveryPickUpStoreApi.updateDeliveryPickUpStore(dataToSubmit)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = assign({}, defaultFormData) // Use assign for proper reset
  formRef.value?.resetFields()
}

/** 打开地图弹窗 */
const openMapDialog = async () => {
  // if (!tencentLbsKey.value) {
  //   await fetchTencentLbsKey(); // Ensure key is fetched before opening map
  // }
  // if (tencentLbsKey.value) {
  //   // Construct the URL for Tencent Map Location Picker
  //   // Docs: https://lbs.qq.com/tool/component-picker.html
  //   tencentLbsUrl.value = `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=${tencentLbsKey.value}&referer=myapp&coord_type=5` // coord_type=5 for GCJ02
  //   // Optional: Add current coords if available: &coord=${formData.value.latitude},${formData.value.longitude}
  //   if (formData.value.latitude && formData.value.longitude) {
  //      tencentLbsUrl.value += `&coord=${formData.value.latitude},${formData.value.longitude}`
  //   }
  //   console.log('Opening map with URL:', tencentLbsUrl.value) // Debug log
  //   mapDialogVisible.value = true
  // } else {
  //   message.error('无法打开地图，缺少地图 Key 配置')
  // }
  mapDialogVisible.value = true
}

/** 选择经纬度 */
const selectAddress = function (loc: any): void {
  if (loc.latlng && loc.latlng.lat) {
    formData.value.latitude = loc.latlng.lat
  }
  if (loc.latlng && loc.latlng.lng) {
    formData.value.longitude = loc.latlng.lng
  }
  mapDialogVisible.value = false
}

/** 初始化腾讯地图 */
const initTencentLbsMap = async () => {
  window.selectAddress = selectAddress
  window.addEventListener(
    'message',
    function (event) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      let loc = event.data
      if (loc && loc.module === 'locationPicker') {
        // 防止其他应用也会向该页面 post 信息，需判断 module 是否为 'locationPicker'
        window.parent.selectAddress(loc)
      }
    },
    false
  )
  // const data = await ConfigApi.getTradeConfig()
  // console.log('data1', data)
  // const key = data.tencentLbsKey
  // const key = 'TVDBZ-TDILD-4ON4B-PFDZA-RNLKH-VVF6E'
  const key = '7MOBZ-6RICQ-DVH5Z-266KV-KCDAF-HNBDP'
  tencentLbsKey.value = '7MOBZ-6RICQ-DVH5Z-266KV-KCDAF-HNBDP'
  // const key = '94ae6ded43533d845451386878cc3264'
  tencentLbsUrl.value = `https://apis.map.qq.com/tools/locpicker?type=1&key=${key}&referer=myapp`
}

/** 处理添加分类点击 */
const handleAddCategory = () => {
    // TODO: 实现添加分类的逻辑，可能需要弹出新窗口或对话框
    message.info("添加分类功能待实现");
}

/** 打开通知人选择弹窗 */
const openNotifierSelectModal = () => {
  message.info('选择通知人功能待实现')
}

/** 打开链接选择弹窗 */
const openLinkSelector = (type: 'h5' | 'mp') => {
  message.info(`选择${type === 'h5' ? 'H5' : '小程序'}链接功能待实现`)
}

onMounted(() => {
  initTencentLbsMap()
})

// 查找区域路径 (返回路径数组或 undefined)
const findAreaPath = async (targetId: number, nodes: AreaVO[]): Promise<number[] | undefined> => {
  for (const node of nodes) {
    if (node.id === targetId) {
      return [node.id];
    }
    if (node.children && node.children.length > 0) {
      const path = await findAreaPath(targetId, node.children);
      if (path && path.length > 0) { // 检查路径是否存在
        return [node.id, ...path];
      }
    }
  }
  console.warn(`Area path not found for targetId: ${targetId}`);
  return undefined; // 未找到时返回 undefined
}

// Fetch Tencent LBS Key
const fetchTencentLbsKey = async () => {
  try {
    // Assuming you have an API or config mechanism to get the key
    // Replace this with your actual key fetching logic
    const config = await ConfigApi.getTradeConfig() // Example API call
    console.log('config', config)
    if (config && config.tencentLbsKey) {
       // tencentLbsKey.value = config.tencentLbsKey
       tencentLbsKey.value = config.tencentLbsKey
       console.log('Tencent LBS Key fetched:', tencentLbsKey.value) // Debug log
    } else {
       console.error('Failed to fetch Tencent LBS Key from config.')
       message.error('获取地图配置失败，无法打开地图')
    }
  } catch (error) {
    console.error('Error fetching Tencent LBS Key:', error)
    message.error('获取地图配置时出错')
  }
}

// Handle messages from the map iframe
const handleMapMessage = (event: MessageEvent) => {
  // IMPORTANT: Add origin check for security
  // Replace 'https://apis.map.qq.com' with the exact origin if different
  // or implement a more robust origin check if necessary
  if (event.origin !== 'https://apis.map.qq.com') {
    console.warn('Ignoring message from unexpected origin:', event.origin);
    return;
  }

  const loc = event.data;
  console.log('Received message from map:', loc); // Debug log

  // Check if it's a location object (from Tencent Location Picker)
  // https://lbs.qq.com/tool/component-picker.html (Refer to documentation for message format)
  if (loc && loc.module === 'locationPicker') {
    const latlng = loc.latlng;
    if (latlng) {
      formData.value.latitude = latlng.lat;
      formData.value.longitude = latlng.lng;
      message.success('坐标已选择');
      mapDialogVisible.value = false; // Close map dialog

      // Optional: Trigger validation after setting values
      nextTick(() => {
        formRef.value?.validateField(['latitude', 'longitude']);
      });
    } else {
       console.warn('Map message received, but latlng data is missing:', loc);
    }
  }
}

// Add and remove message listener
onMounted(() => {
  window.addEventListener('message', handleMapMessage, false);
  // Fetch key when component mounts or when dialog opens?
  // fetchTencentLbsKey(); // Decide when to fetch the key
});

onUnmounted(() => {
  window.removeEventListener('message', handleMapMessage, false);
});
</script>

<style scoped lang="scss">
/* 添加样式使富文本编辑器居中 */
.rich-text-center {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: center; /* 水平居中 */
    /* 如果需要垂直居中，可以添加 align-items: center; 但通常富文本高度自适应 */
  }
  /* 可以根据需要调整编辑器的宽度 */
  :deep(.editor-container) { // 假设 Editor 组件根元素有 .editor-container class
    width: 90%; // 或者设置一个固定的宽度
  }
}

/* 如果需要覆盖 el-form-item 的 label 宽度或其他样式 */
.el-form-item {
  /* 示例：如果需要调整特定 label 的宽度 */
  //&.some-custom-class {
  //  :deep(.el-form-item__label) {
  //    width: 120px; // 自定义宽度
  //  }
  //}
}

/* 针对输入框后附加按钮的样式微调 */
.input-with-select {
  :deep(.el-input-group__append) {
    padding: 0 15px; // 调整按钮内边距
  }
}
</style>
